﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Web.Api.Server.ViewModels
{
    public enum ErrorCode
    {
        Success = 0,
        Fail = 1,
        /// <summary>
        /// 令牌过期
        /// </summary>
        TokenExpired = 10000,
        /// <summary>
        /// 令牌失效
        /// </summary>
        TokenInvalidation = 10010,
        /// <summary>
        /// 数据验证错误
        /// </summary>
        ValidateError = 10400,
        /// <summary>
        /// 没有找到
        /// </summary>
        NotFound = 10404,
    }

    public class ResponseViewModel<T>
    {
        /// <summary>
        /// 错误码
        /// </summary>
        public ErrorCode Code { get; set; }
        /// <summary>
        /// 错误信息
        /// </summary>
        public object Msg { get; set; }
        /// <summary>
        /// 请求地址
        /// </summary>
        public string ReqUrl { get; set; }
    }

    public class ApiResponse
    {
        public static IActionResult Ok<T>(T data, string msg = "done")
        {
            return new OkObjectResult(new ApiViewModel<T>
            {
                Code = ErrorCode.Success,
                Msg = msg,
                Data = data
            });
        }

        public static IActionResult Fail(string msg = "操作失败", ErrorCode errorCode = ErrorCode.Fail)
        {
            var result = new ObjectResult(new ApiViewModel<string>
            {
                Code = errorCode,
                Msg = msg,
                Data = null
            })
            {
                StatusCode = StatusCodes.Status500InternalServerError
            };

            return result;
        }

        public static IActionResult NotFound(string msg = "没有找到相关数据")
        {
            var result = new ObjectResult(new ApiViewModel<string>
            {
                Code = ErrorCode.NotFound,
                Msg = msg,
                Data = null
            })
            {
                StatusCode = StatusCodes.Status500InternalServerError
            };

            return result;
        }

        public static IActionResult ValidateFail<T>(T data)
        {
            return new BadRequestObjectResult(new ApiViewModel<T>
            {
                Code = ErrorCode.ValidateError,
                Msg = "提交数据验证错误",
                Data = data
            });
        }
    }

    public class ApiViewModel<T>
    {
        /// <summary>
        /// 返回结果状态 0成功 4001数据验证错误 404没有找到 500内部错误
        /// </summary>
        public ErrorCode Code { get; set; }
        /// <summary>
        /// 描述信息
        /// </summary>
        public string Msg { get; set; }
        public T Data { get; set; }
    }
}
